package com.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//路由
@Controller
public class RouteController {
    @RequestMapping({"/","/index"})
    public String index(){
        return  "index";
    }
    @RequestMapping({"/toLogin"})
    public String login(){
        return  "views/login";
    }

    @RequestMapping({"/level1/{id}"})
    public String level1(@PathVariable("id") int id){
        return  "views/level1/"+id;
    }

    @RequestMapping({"/level2/{id}"})
    public String level2(@PathVariable("id") int id){
        return  "views/level2/"+id;
    }

    @RequestMapping({"/level3/{id}"})
    public String level3(@PathVariable("id") int id){
        return  "views/level3/"+id;
    }


    @PostMapping("/usr/login")
    public String login(String username, String password, Model model) {
        // 获取用户
        Subject user = SecurityUtils.getSubject();
        // 封装参数，获取token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 验证登录
        try {
            // 执行登录操作，跨类调用
            user.login(token);
            model.addAttribute("msg", "成功登录");
            return "redirect:/";
        } catch (UnknownAccountException uae) {
            model.addAttribute("msg", "用户名错误");
            return "views/login";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg", "用户密码错误");
            return "views/login";
        }catch (AuthenticationException exception){
            model.addAttribute("msg", "配置错误");
            return "views/login";
        }
    }

    @RequestMapping("/noAuth")
    @ResponseBody
    public String noAuth() {
        return "未授权，无法访问";
    }

}
